#include "json_syntaxhighlight.h"

JsonSyntaxHighlight::JsonSyntaxHighlight(QTextDocument* parent)
    : QSyntaxHighlighter(parent)
{
    this->initRules();
}

void JsonSyntaxHighlight::highlightBlock(const QString& text)
{
    for (const _HightRule& rule : _rules) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
}

void JsonSyntaxHighlight::initRules()
{
    _HightRule rule;

    // 数字
    rule.format.setForeground(QColor(75, 131, 231));
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("-?\\d+\\.?\\d*");
    _rules << rule;

    // 字符串
    rule.format.setForeground(Qt::darkGreen);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\"[^\"]*\"");
    _rules << rule;

    // 布尔
    rule.format.setForeground(QColor(242, 129, 142));
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\btrue|false\\b");
    _rules << rule;

    // null
    rule.format.setForeground(Qt::gray);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\bnull\\b");
    _rules << rule;

    // 键
    rule.format.setForeground(Qt::darkBlue);
    rule.format.setFontWeight(QFont::Bold);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\"\\w*\"(?=\\s*:)");
    _rules << rule;
}
